package com.hg.library.manager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.hispot.download.FileDownloadStatus;

/**
 * Created by admin on 2017/3/14.
 */

/*
 应用商店专用类，用于应用商店点击开始下载 发送广播进行通知
 */
public class AppStoreInteraction extends BroadcastReceiver {
    private Context mContext;

    public static final String START_DOWNLOAD_ACTION = "android.intent.START_DOWNLOAD_ACTION";

    private OnFileDownloadBegin onFileDownloadBegin;

    public AppStoreInteraction(Context mContext) {
        this.mContext = mContext;
    }

    public void setOnFileDownloadBegine(OnFileDownloadBegin onFileDownloadBegin) {
        this.onFileDownloadBegin = onFileDownloadBegin;
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        int state = intent.getIntExtra("state", -1);

        String iconUrl = intent.getStringExtra("iconUrl");
        String packageName = intent.getStringExtra("packageName");
        String title = intent.getStringExtra("title");
        String downloadUrl = intent.getStringExtra("downloadUrl");

        if (onFileDownloadBegin != null) {
            if (state == FileDownloadStatus.Start) {

                onFileDownloadBegin.onBeginning(iconUrl, downloadUrl, packageName, title);
            } else if (state == FileDownloadStatus.Pause) {
                onFileDownloadBegin.onPause(iconUrl, downloadUrl, packageName, title);
            }
        }
    }

    public void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(START_DOWNLOAD_ACTION);
        mContext.registerReceiver(this, intentFilter);
    }

    public void detachReceiver() {
        mContext.unregisterReceiver(this);
    }

    public interface OnFileDownloadBegin {
        void onBeginning(String iconUrl, String downloadUrl, String packageName, String title);

        void onPause(String iconUrl, String downloadUrl, String packageName, String title);
    }

    public void sendOnBeginningDownloadInfo(int state, String iconUrl, String downloadUrl, String packageName, String title) {
        Intent intent = new Intent();
        intent.setAction(START_DOWNLOAD_ACTION);
        intent.putExtra("state", state);
        intent.putExtra("iconUrl", iconUrl);
        intent.putExtra("downloadUrl", downloadUrl);
        intent.putExtra("packageName", packageName);
        intent.putExtra("title", title);

        mContext.sendBroadcast(intent);
    }
}
